/*
 * @Author: 飞越疯人院 353362604@qq.com
 * @Date: 2022-12-18 09:46:33
 * @LastEditors: 飞越疯人院 353362604@qq.com
 * @LastEditTime: 2022-12-19 16:37:09
 * @FilePath: \adminstration\src\Common\Modal\MoreModal\tinymce.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Editor } from '@tinymce/tinymce-react'
import { useRef, useState, useEffect } from 'react'
import { Button, Input, DatePicker, Divider, Upload, message, Tooltip, Spin } from 'antd'
import { LoadingOutlined, PlusOutlined, LinkOutlined, DeleteOutlined } from '@ant-design/icons'
import { API_LIST } from '../../Api/Api'
import { Http } from '../../Api'
import { useBoolean, useRequest } from 'ahooks'
import dayjs from 'dayjs'
import { CopyToClipboard } from 'react-copy-to-clipboard'

const beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) message.error('请双穿 jpg/png 图片!')
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) message.error('图片大小不得超过2M!')
    return isJpgOrPng && isLt2M
}

export const TinyMce = ({ data }) => {
    const [Data, setData] = useState(data)
    const editorRef = useRef(null)
    const [TableName, setTableName] = useState()
    const [EventDate, setEventDate] = useState()
    const [imageUrl, setImageUrl] = useState()
    const [Content, setContent] = useState()
    const [fileList, setFileList] = useState([])
    const [loading, setLoading] = useState(false)

    const [State, { setTrue, setFalse }] = useBoolean(false)

    const uploadButton = <div> {loading ? <LoadingOutlined /> : <PlusOutlined />} </div>
    const { runAsync: putInfoManage } = useRequest(Http, { manual: true })
    const { runAsync: delInfoManageDetail } = useRequest(Http, { manual: true })
    const { runAsync: posInfoManageDetail } = useRequest(Http, { manual: true })

    const { runAsync: getInfoManageDetail } = useRequest(Http, {
        manual: true,
        onSuccess: ({ list }) => {
            if (list.length !== 0) {
                let ImageList = list.map(item => ({
                    uid: item.uuid,
                    name: item.tableName,
                    url: item.fileUrl,
                    status: 'done',
                }))
                setFileList(ImageList)
            }
        },
    })

    const { runAsync: getInfoManageGetOneInfoManage } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            const [data] = res
            setData(Data)
            setTableName(data.tableName)
            setEventDate(dayjs(data.eventDate))
            setImageUrl(data.coverUrl)
            setContent(data.infoContent)
            getInfoManageDetail({ url: 'getInfoManageDetail', data: { InfoManageUuid: data.uuid } })
        },
    })

    useEffect(() => {
        getInfoManageGetOneInfoManage({ url: 'getInfoManageGetOneInfoManage', data: { uuid: data.uuid } })
    }, [data, getInfoManageGetOneInfoManage])

    const handleChange = info => {
        if (info.file.status === 'uploading') {
            setLoading(true)
            return
        }
        if (info.file.status === 'done') {
            const { fileUrl, uuid } = info.file.response
            putInfoManage({
                url: 'putInfoManage',
                data: { ...data, coverAttachmentUuid: uuid, infoContent: editorRef.current.getContent() },
                path: [data.uuid],
            })
                .then(res => {
                    message.success('封面上传成功!')
                    setData({ ...Data, coverAttachmentUuid: res.coverAttachmentUuid })
                    setLoading(false)
                    setImageUrl(fileUrl)
                })
                .catch(() => {
                    message.error('封面上传失败!')
                    setLoading(false)
                })
        }
    }

    const handleChangeList = info => {
        if (info.file.status === 'uploading') {
            setFileList(info.fileList)
            setLoading(true)
            return
        }
        if (info.file.status === 'done') {
            const { uuid } = info.file.response
            posInfoManageDetail({
                url: 'posInfoManageDetail',
                data: { InfoManageUuid: data.uuid, tableName: data.tableName, attachmentUuid: uuid },
            })
                .then(() => {
                    message.success('图片上传成功!')
                    getInfoManageDetail({ url: 'getInfoManageDetail', data: { InfoManageUuid: data.uuid } })
                    setLoading(false)
                })
                .catch(() => {
                    message.error('图片上传失败!')
                    setLoading(false)
                })
        }
    }

    const SubmitEditor = () => {
        if (!TableName) {
            message.error('请输入文章主题!')
            return
        } else {
            setTrue()
            let param = {
                ...Data,
                tableName: TableName,
                eventDate: dayjs(EventDate).format('YYYY-MM-DD HH:mm:ss'),
                infoContent: editorRef.current.getContent(),
            }
            putInfoManage({ url: 'putInfoManage', data: param, path: [Data.uuid] })
                .then(() => {
                    message.success('文章保存成功')
                    setFalse()
                })
                .catch(() => message.error('文章保存失败'))
        }
    }

    return (
        <Spin spinning={State}>
            <div className="TinyMce">
                <div>
                    <div>
                        <div>主题 : </div>
                        <Input
                            placeholder="请输入文章主题"
                            value={TableName}
                            onChange={e => setTableName(e.target.value)}
                        />
                    </div>
                    <div>
                        <div>时间 : </div>
                        <DatePicker value={EventDate} onChange={e => setEventDate(e)} showTime />
                    </div>
                </div>
                <div>
                    <div>
                        <Divider>封面</Divider>
                        <div>
                            <Upload
                                name="file"
                                action={API_LIST()['posAttachment']}
                                data={{ fileType: 1 }}
                                headers={{ Authorization: `${sessionStorage.getItem('TOKEN')}` }}
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                beforeUpload={beforeUpload}
                                onChange={handleChange}
                            >
                                {imageUrl ? (
                                    <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                                ) : (
                                    uploadButton
                                )}
                            </Upload>
                        </div>
                    </div>
                    <Divider type="vertical" />
                    <div>
                        <Divider>附件</Divider>
                        <Upload
                            name="file"
                            action={API_LIST()['posAttachment']}
                            data={{ fileType: 1 }}
                            headers={{ Authorization: `${sessionStorage.getItem('TOKEN')}` }}
                            listType="picture-card"
                            fileList={fileList}
                            onChange={handleChangeList}
                            onRemove={() => false}
                            onDownload={() => false}
                            showUploadList={{
                                showPreviewIcon: false,
                                showRemoveIcon: true,
                                showDownloadIcon: true,
                                downloadIcon: e => (
                                    <Tooltip title="复制链接">
                                        <CopyToClipboard
                                            text={e.url}
                                            onCopy={() => message.success('图片地址复制成功!')}
                                        >
                                            <LinkOutlined style={{ fontSize: 20, color: 'white' }} />
                                        </CopyToClipboard>
                                    </Tooltip>
                                ),
                                removeIcon: e => (
                                    <Tooltip title="删除图片">
                                        <DeleteOutlined
                                            style={{ fontSize: 20, color: 'red' }}
                                            onClick={() => {
                                                console.log(e)
                                                delInfoManageDetail({ url: 'delInfoManageDetail', path: [e.uid] })
                                                    .then(() => {
                                                        message.success('图片删除成功')
                                                        getInfoManageDetail({
                                                            url: 'getInfoManageDetail',
                                                            data: { InfoManageUuid: data.uuid },
                                                        })
                                                    })
                                                    .catch(() => message.error('图片删除失败'))
                                            }}
                                        />
                                    </Tooltip>
                                ),
                            }}
                        >
                            {fileList.length >= 8 ? null : uploadButton}
                        </Upload>
                    </div>
                </div>
                <div>
                    <Editor
                        apiKey="5b9brap9x1rvhy1ixyk6bzvxi3ensl97vz0q3g5pg3y88xfo"
                        onInit={(_, editor) => (editorRef.current = editor)}
                        initialValue={Content ? Content : '<p>请在这里输入文章内容.</p>'}
                        init={{
                            language: 'zh_CN',
                            height: 500,
                            menubar: true,
                            removed_menuitems: 'newdocument ,visualaid',
                            branding: false,
                            // elementpath: false,
                            // resize: false,
                            // statusbar: false,
                            plugins: [
                                'advlist autolink lists link image charmap print preview anchor',
                                'searchreplace visualblocks code fullscreen',
                                'insertdatetime media table paste code  wordcount',
                                'image',
                            ],
                            toolbar:
                                ' undo redo | formatselect | bold italic backcolor | alignleft aligncenter ' +
                                'alignright alignjustify | bullist numlist outdent indent | removeformat  |image ',
                        }}
                    />
                </div>
                <div>
                    <Button type="primary" onClick={SubmitEditor}>
                        保存
                    </Button>
                </div>
            </div>
        </Spin>
    )
}
